const bcrypt = require('bcryptjs')
const { query } = require('../config/database')

async function createAdmin () {
  try {
    console.log('🔍 检查管理员账号...')

    // 检查是否已有admin@novel.com用户
    const adminUser = await query('SELECT * FROM users WHERE email = ?', [
      'admin@novel.com'
    ])

    if (adminUser.length === 0) {
      console.log('📝 正在创建管理员账号...')
      const password = await bcrypt.hash('admin123', 12)

      await query(
        'INSERT INTO users (username, email, password_hash, nickname, is_vip, coins) VALUES (?, ?, ?, ?, ?, ?)',
        ['admin', 'admin@novel.com', password, '管理员', 1, 9999]
      )

      console.log('✅ 管理员账号创建成功！')
      console.log('')
      console.log('🔑 登录信息：')
      console.log('   邮箱: admin@novel.com')
      console.log('   密码: admin123')
      console.log('')
    } else {
      console.log('✅ 管理员账号已存在')
      console.log('')
      console.log('🔑 登录信息：')
      console.log('   邮箱: admin@novel.com')
      console.log('   密码: admin123')
      console.log('')
    }

    // 也检查admin@example.com
    const adminUser2 = await query('SELECT * FROM users WHERE email = ?', [
      'admin@example.com'
    ])

    if (adminUser2.length === 0) {
      console.log('📝 正在创建备用管理员账号...')
      const password = await bcrypt.hash('123456', 12)

      await query(
        'INSERT INTO users (username, email, password_hash, nickname, is_vip, coins) VALUES (?, ?, ?, ?, ?, ?)',
        ['admin2', 'admin@example.com', password, '管理员2', 1, 9999]
      )

      console.log('✅ 备用管理员账号创建成功！')
      console.log('')
      console.log('🔑 备用登录信息：')
      console.log('   邮箱: admin@example.com')
      console.log('   密码: 123456')
      console.log('')
    } else {
      console.log('✅ 备用管理员账号已存在')
      console.log('')
      console.log('🔑 备用登录信息：')
      console.log('   邮箱: admin@example.com')
      console.log('   密码: 123456')
      console.log('')
    }

    // 显示所有用户
    const allUsers = await query(
      'SELECT id, username, email, nickname, is_vip, coins FROM users'
    )
    console.log('📋 所有用户列表:')
    console.table(allUsers)
  } catch (error) {
    console.error('❌ 错误:', error.message)
  }

  process.exit(0)
}

createAdmin()
